﻿using System;
using Slwy.Utility.Extensions;
using SqlSugar;

namespace Slwy.Data.Entity.Helper
{
    public static class TableHelper
    {
        /// <summary>
        /// 获取表名
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="keyId"></param>
        /// <param name="formatData"></param>
        /// <exception cref="System.ArgumentException">>如果从keyId获取表名失败引发异常</exception>
        /// <returns></returns>
        public static string GetTableName<T>(string keyId = "", string formatData = "YY")
        {
            var member = typeof(T).GetAttribute<SugarTable>();
            var tableName = member?.TableName;
            if (tableName.IsNullOrEmpty())
            {
                tableName = typeof(T).Name.Replace("Entity","");
            }

            if (keyId.IsNullOrEmpty())
            {
                return tableName;
            }

            var dateTime = string.Empty;
            if (formatData == "YY")
            {
                dateTime = keyId.Substring(0, 2);
            }

            if (formatData == "YYMM")
            {
                dateTime = keyId.Substring(0, 4);
            }

            if (!dateTime.IsNumber())
            {
                throw new ArgumentException($"尝试从 keyId:{keyId} 获取表名是发生错误, keyId 可能不是一个有效的值");
            }

            return tableName + "20" + dateTime;
        }
    }
}
